package mysql

import (
	"nil/models"
	"strings"

	"github.com/jmoiron/sqlx"
)

// CreatePost 创建帖子
func CreatePost(p *models.Post) (err error) {
	sqlStr := `insert into post(
	post_id, title, content, author_id, chunk_id,status)
	values (?, ?, ?, ?, ?,?)
	`
	_, err = db.Exec(sqlStr, p.ID, p.Title, p.Content, p.AuthorID, p.ChunkID, p.Status)
	return
}

// GetPostByID  根据ID查询一条帖子的详情信息
func GetPostByID(pid int64) (post *models.Post, err error) {
	post = new(models.Post)
	sqlStr := `select 
    post_id,title,content,author_id,chunk_id,create_time 
	from post where post_id=?`
	err = db.Get(post, sqlStr, pid)
	return
}

// GetPostList  查询帖子列表函数
func GetPostList(offset, limit int64) (posts []*models.Post, err error) {
	sqlStr := `select 
    post_id,title,content,author_id,chunk_id,create_time 
	from post 
	ORDER BY create_time
	DESC 
	limit ?,?
	`
	posts = make([]*models.Post, 0, 2) //不要写成make([]*models.ApiPostDetail,2)
	err = db.Select(&posts, sqlStr, (offset-1)*limit, limit)
	return
}

// GetPostListByIDs  根据给点的id列表查询帖子数据
func GetPostListByIDs(ids []string) (data []*models.Post, err error) {
	sqlStr := `select post_id,title,content,author_id,chunk_id,create_time
			from post
			where post_id in (?)
			order by FIND_IN_SET(post_id,?)
			    `

	//https://www.liwenzhou.com/posts/Go/sqlx/
	query, args, err := sqlx.In(sqlStr, ids, strings.Join(ids, ","))
	if err != nil {
		return nil, err
	}

	query = db.Rebind(query)
	err = db.Select(&data, query, args...) //!!!!别忘记最后的 ...
	return
}
